package security;

import java.sql.*;
import db.*;

/**
 * 用户安全类
 * @author Shi Mengjie
 * @version 1.0
 */
public final class UserSecurityBiz {
	/**
	 * 该方法验证用户id为uid的用户是否拥有管理员权限
	 * @param uid
	 * @return boolean
	 */
	public static boolean isAdmin(int uid){
		if (uid == 0) return false;
		boolean ret = false;
		
		DBConn dbc = new DBConn();
		Connection conn  = dbc.getConn();
		PreparedStatement prepSt = null;
		ResultSet rs = null;
		String sqlQuery = "select * from admin where uid = ? ";
		try{
			prepSt = conn.prepareStatement(sqlQuery);
			prepSt.setInt(1, uid);
			rs = prepSt.executeQuery();
			while (rs.next()){
				ret = true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBBiz.closeResultSet(rs);
			DBBiz.closePreparedStatement(prepSt);
			DBBiz.closeConnection(conn);
		}
		
		return ret;
	}
	
	/**
	 * 为指定的明文密码生成MD5值的存储密码
	 * @param password
	 * @return String
	 */
	public static String GenerateStorePassword(String password){
		return Encryption.getMD5(password);
	}
	
	/**
	 * 检测用户id为uid的用户当前密码是否为password
	 * @param uid
	 * @param password
	 * @return boolean
	 */
	public static boolean CheckUserByUid(int uid, String password){
		String upass = Encryption.getMD5(password);
		boolean ret = false;
		
		DBConn dbc = new DBConn();
		Connection conn  = dbc.getConn();
		PreparedStatement prepSt = null;
		ResultSet rs = null;
		String sqlQuery = "select * from users where uid = ? and upass = ? ";
		try{
			prepSt = conn.prepareStatement(sqlQuery);
			prepSt.setInt(1, uid);
			prepSt.setString(2, upass);
			rs = prepSt.executeQuery();
			while (rs.next()){
				ret = true;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBBiz.closeResultSet(rs);
			DBBiz.closePreparedStatement(prepSt);
			DBBiz.closeConnection(conn);
		}
		
		return ret;
	}
	
	public static boolean InsertAdmin(int uid){
		boolean flag = false;
		DBConn dbc = new DBConn();
		Connection conn  = dbc.getConn();
		PreparedStatement prepSt = null;
		
		String sqlInsert = "insert into admin(uid) values(?)";
		try{
			prepSt = conn.prepareStatement(sqlInsert);
			prepSt.setInt(1, uid);
			prepSt.execute();
			flag = true;
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally{
			DBBiz.closePreparedStatement(prepSt);
			DBBiz.closeConnection(conn);
		}
		
		System.out.println(flag);
		return flag;
	}
}
